﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.ETL.Domain.Services
{
    public class EBSService
    {
        /// <summary>
        /// 本系统的基地址，从webconfig里读取
        /// </summary>
        private static string s_webAddress;

        /// <summary>
        /// ebs回调本系统的地址
        /// </summary>
        public static string CallbackUrl { get; private set; }

        /// <summary>
        /// 初始化，读取ebs配置信息，
        /// 获取任务信息，将事件触发模式的任务注册到ebs
        /// </summary>
        /// <param name="proxyConfigFile"></param>
        /// <param name="callbackRelativeUrl"></param>
        /// <returns></returns>
        public static bool Init(string proxyConfigFile, string callbackRelativeUrl)
        {
            if(!CPPEI.EBS.Proxy.EBSProxy.InitWithConfig(proxyConfigFile))
            {
                return false;
            }
            s_webAddress = System.Configuration.ConfigurationManager.AppSettings["WebBaseAddress"];
            CallbackUrl = string.Format("{0}{1}", s_webAddress, callbackRelativeUrl);

            using(EtlDbContext dbContext = new EtlDbContext())
            {
                EntityRepository<Views.VEventModeTask> vmtRep = new EntityRepository<Views.VEventModeTask>(dbContext);
                List<Views.VEventModeTask> taskList = vmtRep.Query().ToList();
            }
            return true;
        }

        public void Register(string @event)
        {
            Logger.InfoToTag(Library.LogTAG, string.Format("Register:{0},callback:{1}", @event, CallbackUrl));
            try
            {
                CPPEI.EBS.Proxy.EBSProxy.Register("ETL", @event, CallbackUrl);
            }
            catch (Exception ex)
            {
                Logger.ErrorToTag(Library.LogTAG, string.Format("Register:{0},callback:{1}出错,ex:{2}", @event, CallbackUrl, ex));
            }
        }

        public void Unregister(string @event)
        {
            try
            {
                Logger.InfoToTag(Library.LogTAG, string.Format("Unregister:{0},callback:{1}", @event, CallbackUrl));
                CPPEI.EBS.Proxy.EBSProxy.Unregister("ETL", @event);
            }
            catch (Exception ex)
            {
                Logger.ErrorToTag(Library.LogTAG, string.Format("Unregister:{0},callback:{1}出错,ex:{2}", @event, CallbackUrl, ex));
            }
        }

        public void Publish(string @event, string data)
        {
            Logger.InfoToTag(Library.LogTAG, string.Format("Publish:{0},data:{1}", @event, data));
            try
            {
                CPPEI.EBS.Proxy.EBSProxy.Publish("ETL", @event, data);
            }
            catch(Exception ex)
            {
                Logger.ErrorToTag(Library.LogTAG, string.Format("Publish:{0},data:{1}出错,ex:{2}", @event, data, ex));
            }
        }

        /// <summary>
        /// 注册所有的事件执行模式的任务到ebs
        /// </summary>
        public static ServiceResult<Data.Register2EBSResult> RegisterAllEventTask()
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                Data.Register2EBSResult result = new Data.Register2EBSResult();

                EntityRepository<Views.VEventModeTask> ertRep = new EntityRepository<Views.VEventModeTask>(dbContext);
                List<Views.VEventModeTask> list = null;

                try
                {
                    list = ertRep.Query().ToList();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("获取事件处理模式的任务出错,ex:{0}", ex));
                    return new ServiceResult<Data.Register2EBSResult>(false, ErrorCode.COM_Exception, ErrorCode.String(ErrorCode.COM_Exception));
                }

                for (int index = 0; index < list.Count; index++)
                {
                    try
                    {
                        new EBSService().Register(list[index].EventName);

                        Data.Register2EBSResult.Item item = new Data.Register2EBSResult.Item();
                        item.TaskId = list[index].Id;
                        item.EventName = list[index].EventName;
                        item.IsSuccess = true;
                        item.Message = "注册成功";
                        item.TaskName = list[index].Name;
                        result.Items.Add(item);
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorToTag(Library.LogTAG, string.Format("注册事件:{0}到ebs出错,ex:{1}", list[index].EventName, ex));

                        Data.Register2EBSResult.Item item = new Data.Register2EBSResult.Item();
                        item.TaskId = list[index].Id;
                        item.EventName = list[index].EventName;
                        item.IsSuccess = false;
                        item.Message = ex.Message;
                        item.TaskName = list[index].Name;
                        result.Items.Add(item);
                    }
                }
                return new ServiceResult<Data.Register2EBSResult>(true, ErrorCode.COM_NoError, ErrorCode.String(ErrorCode.COM_NoError), result);
            }
        }
    }
}
